<script setup lang="ts">
import { onMounted, ref, watch,computed } from 'vue';
import { useUserStore } from '../stores/userStore';
import { storeToRefs } from 'pinia';
import AddUserForm from '../components/user/AddUserForm.vue';
import SetUserRoleForm from '../components/user/SetUserRoleForm.vue';
import RolePermissionForm from '../components/user/RolePermissionForm.vue';
import { API_CONFIG } from '../config/apiConfig';

const userStore = useUserStore();
const { filteredUsers, currentPage, pageSize, searchQuery, filteredTotal } = storeToRefs(userStore);
const showAddUserForm = ref(false);
const showSetRoleForm = ref(false);
const showRolePermissionForm = ref(false);
const selectedUserId = ref<string | null>(null);

const handleUserAdded = () => {
  showAddUserForm.value = false;
  userStore.fetchUsers();
};

const notification = ref({
  show: false,
  message: '',
  type: '' // 'success' or 'error'
});

// 计算当前页应显示的用户数据
const paginatedUsers = computed(() => {
  if (!searchQuery.value) {
    // 没有搜索时，直接使用后端分页的数据
    return filteredUsers.value;
  } else {
    // 有搜索时，在前端进行分页
    const start = (currentPage.value - 1) * pageSize.value;
    const end = start + pageSize.value;
    return filteredUsers.value.slice(start, end);
  }
});

const handleDelete = async (userId: string) => {
  if (!confirm('确定要删除该用户吗？')) return;
  
  try {
    const response = await fetch(`${API_CONFIG.BASE_URL}/user/${userId}`, {
      method: 'DELETE',
      credentials: 'include'
    });
    const result = await response.json();

    if (result.code === "0") {
      // 删除成功后更新本地用户列表
      userStore.users = userStore.users.filter(user => user.id !== userId);
      // 显示成功提示
      notification.value = {
        show: true,
        message: '删除成功',
        type: 'success'
      };
      // 3秒后自动隐藏
      setTimeout(() => {
        notification.value.show = false;
      }, 3000);
    } else {
      notification.value = {
        show: true,
        message: `删除失败: ${result.msg}`,
        type: 'error'
      };
      setTimeout(() => {
        notification.value.show = false;
      }, 3000);
    }
  } catch (error) {
    console.error('删除请求失败:', error);
    notification.value = {
      show: true,
      message: '删除失败，请检查网络连接',
      type: 'error'
    };
    setTimeout(() => {
      notification.value.show = false;
    }, 3000);
  }
};

const handleSetRole = (userId: string) => {
  selectedUserId.value = userId;
  showSetRoleForm.value = true;
};

const handleRoleUpdated = () => {
  userStore.fetchUsers();
};

const handlePermissionsUpdated = () => {
  // 权限更新后可能需要刷新用户列表或其他操作
  userStore.fetchUsers();
};


// 页面加载时获取用户数据
onMounted(() => {
  userStore.fetchUsers();
});

// 监听页码变化
watch(() => userStore.currentPage, () => {
  // 只有在没有搜索查询时才从服务器获取数据
  if (!searchQuery.value) {
    userStore.fetchUsers();
  }
});

// 输入框通过v-model直接绑定searchQuery，无需额外handleSearch
// 移除handleSearch函数
</script>

<template>
  <div class="user-management">
    <div class="header">
      <h1>用户管理</h1>
      <div class="header-buttons">
        <button class="add-user-btn" @click="showAddUserForm = true">新增用户</button>
        <button class="role-permission-btn" @click="showRolePermissionForm = true">角色权限管理</button>
      </div>
    </div>

    <div class="modal" v-if="showAddUserForm">
      <div class="modal-content">
        <AddUserForm 
          @close="showAddUserForm = false"
          @user-added="handleUserAdded"
        />
      </div>
    </div>

    <div class="modal" v-if="showSetRoleForm">
      <div class="modal-content">
        <SetUserRoleForm 
          v-if="selectedUserId"
          :userId="selectedUserId"
          @close="showSetRoleForm = false"
          @role-updated="handleRoleUpdated"
        />
      </div>
    </div>

    <div class="modal" v-if="showRolePermissionForm">
      <div class="modal-content">
        <RolePermissionForm 
          @close="showRolePermissionForm = false"
          @permissions-updated="handlePermissionsUpdated"
        />
      </div>
    </div>

    <div class="search-container">
      <input 
        type="text" 
        placeholder="搜索" 
        class="search-input"
        v-model="searchQuery"
      />
    </div>

    

    <div class="users-table">
      <table>
        <thead>
          <tr>
            <th>ID</th>
            <th>昵称</th>
            <th>账号</th>
            <th>权限</th>
            <th>实验室名称</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="user in paginatedUsers" :key="user.id">
            <td>{{ user.id }}</td>
            <td>{{ user.nickname }}</td>
            <td>
              <span class="role-badge" :class="user.nickname.replace(' ', '_')">
                {{ user.username }}
              </span>
            </td>
            <td>{{ user.roleName }}</td>
            <td>{{ user.researchGroupName }}</td>
            <td>
              <template v-if="user.roleName !== '超级管理员'">
                <button class="edit-btn" @click="handleSetRole(user.id)">修改权限</button>
                <button class="delete-btn" @click="handleDelete(user.id)">删除</button>
              </template>
              <span v-else class="no-actions">-</span>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    

    <div class="pagination">
      <button 
        class="page-btn" 
        @click="currentPage = Math.max(1, currentPage - 1)"
        :disabled="currentPage === 1"
      >
        &lt;
      </button>
      <button 
        v-for="page in Math.ceil(filteredTotal / pageSize)" 
        :key="page"
        class="page-btn"
        :class="{ active: page === currentPage }"
        @click="currentPage = page"
      >
        {{ page }}
      </button>
      <button 
        class="page-btn" 
        @click="currentPage = Math.min(Math.ceil(filteredTotal / pageSize), currentPage + 1)"
        :disabled="currentPage === Math.ceil(filteredTotal / pageSize)"
      >
        &gt;
      </button>
    </div>

    
  </div>

  <!-- 通知气泡 -->
  <transition name="fade">
    <div v-if="notification.show" class="notification" :class="notification.type">
      {{ notification.message }}
    </div>
  </transition>
</template>

<style scoped>
.user-management {
  padding: 24px;
  max-width: 1400px;
  margin: 0 auto;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.header h1 {
  font-size: 24px;
  font-weight: 600;
}

.header-buttons {
  display: flex;
  gap: 12px;
}

.add-user-btn,
.role-permission-btn {
  background-color: #3b82f6;
  color: white;
  border: none;
  border-radius: 8px;
  padding: 8px 16px;
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.2s;
}

.add-user-btn:hover,
.role-permission-btn:hover {
  background-color: #2563eb;
}

.modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background-color: white;
  padding: 20px;
  border-radius: 8px;
  max-width: 600px;
  width: 100%;
}

.search-container {
  margin-bottom: 24px;
}

.search-input {
  width: 100%;
  padding: 12px;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  background-color: #f9fafb;
  font-size: 14px;
}

.users-table {
  background-color: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

table {
  width: 100%;
  border-collapse: collapse;
}

th, td {
  padding: 12px 16px;
  text-align: left;
  border-bottom: 1px solid #e5e7eb;
}

th {
  background-color: #f9fafb;
  font-weight: 500;
  color: #6b7280;
}

.role-badge, .status-badge {
  padding: 4px 8px;
  border-radius: 16px;
  font-size: 12px;
  font-weight: 500;
}

.role-badge.admin {
  background-color: #e0f2fe;
  color: #0369a1;
}

.role-badge.editor {
  background-color: #f3e8ff;
  color: #7e22ce;
}

.role-badge.viewer {
  background-color: #f3f4f6;
  color: #4b5563;
}

.status-badge.active {
  background-color: #dcfce7;
  color: #15803d;
}

.status-badge.inactive {
  background-color: #fee2e2;
  color: #b91c1c;
}

.edit-btn {
  color: #3b82f6;
  background: none;
  border: none;
  cursor: pointer;
  font-weight: 500;
  margin-right: 8px;
}

.delete-btn {
  color: #f63b41;
  background: none;
  border: none;
  cursor: pointer;
  font-weight: 500;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 8px;
  margin-top: 24px;
}

.page-btn {
  padding: 8px 12px;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  background: white;
  cursor: pointer;
}

.page-btn.active {
  background-color: #3b82f6;
  color: white;
  border-color: #3b82f6;
}

/* 通知样式 */
.notification {
  position: fixed;
  bottom: 20px;
  right: 20px;
  padding: 12px 24px;
  border-radius: 8px;
  color: white;
  font-size: 14px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  z-index: 1000;
}

.notification.success {
  background-color: #10b981;
}

.notification.error {
  background-color: #ef4444;
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.5s;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
</style>